package ini

import (
	"fmt"
	"os"
	"gitee.com/yang-wenli/ini/fsnotify"
	"runtime"
)

type ListenFunc func(string)
type Listener interface {
	listen(string)
}

// Parse将指定的文件名翻译成File类型，里面存储了配置信息
func Parse(filename string) (*File, error) {
	file, err := os.Open(filename)
	if err != nil {
		return nil, err
	}

	comment := '#'
	if runtime.GOOS == "windows" {
		comment = ';'
	}
	return parse(file, byte(comment))
}

func Watch(filename string, listener interface{}) (*File, error) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return nil, err
	}

	go func() {
		for {
			select {
				case event, ok := <-watcher.Events:
					if !ok {
						return
					}
					if event.Op&fsnotify.Write == fsnotify.Write {
						switch listener.(type) {
							case func(string):
								fun := listener.(func(string))
								fun(event.Name)
							case ListenFunc:
								fun := listener.(ListenFunc)
								fun(event.Name)
							case Listener:
								lis := listener.(Listener)
								lis.listen(event.Name)
							default:
								return
						}
					}
				case err, ok := <-watcher.Errors:
					if !ok {
						return
					}
					fmt.Println(err)
			}
		}
	}()

	err = watcher.Add(filename)
	if err != nil {
		return nil, err
	}
	return Parse(filename)
}
